import { createRouter, createWebHistory } from 'vue-router'
import { _import } from './_import'
import store from '../stores'
import NProgress from '@/utils/nprogress'

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/login',
    component: _import('common/login'),
    meta: {
      title: '登录',
      whiteList: true
    }
  },
  {
    path: '/aLogin',
    component: _import('common/adminLogin'),
    meta: {
      title: '登录',
      whiteList: true
    }
  },
  {
    path: '/loading',
    component: _import('common/loading'),
    meta: {
      title: '正在进入...',
      whiteList: true
    }
  },
  {
    path: '/auth',
    component: _import('common/auth'),
    meta: {
      title: '无权限',
      whiteList: true
    }
  },
  {
    path: '/index',
    name: 'index',
    component: _import('index/index'),
    meta: {
      title: '水老板-带你赚大钱'
    }
  },
  {
    path: '/customer',
    name: 'customer',
    component: _import('customer/index'),
    meta: {
      title: '客户管理',
      perms: ['admin']
    }
  },
  {
    path: '/product',
    name: 'product',
    component: _import('product/index'),
    meta: {
      title: '持仓管理',
      perms: ['admin']
    }
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  },
  {
    path: '/404',
    component: _import('common/404'),
    meta: {
      title: 404,
      whiteList: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_PATH),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const title = to.meta && to.meta.title
  if (title) {
    document.title = title
  }
  const { user } = store
  if (to.meta.whiteList) {
    if (['/aLogin', '/login'].includes(to.path)) {
      if (user.getToken()) {
        next({
          path: '/index',
          replace: true
        })
      } else {
        store.user.clearUserInfo()
        next()
      }
    } else {
      next()
    }
  } else {
    if (user.getToken()) {
      // 判断是否有权限
      const userInfo = user.getUserInfo()
      if (to.meta.perms && !to.meta.perms.includes(userInfo.type)) {
        next({
          path: '/auth',
          replace: true
        })
      }
      next()
    } else {
      next({
        path: '/login',
        replace: true
      })
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
